package org.sfx.io

import java.io.PrintWriter

class IndentPrintWriter(writer: PrintWriter, autoFlush: Boolean = true) extends PrintWriter(writer, autoFlush) {
  private var column = 0
  private var indent = 0
  var indentSize = 3
  
  override def write(c: Int): Unit = {
    if (column < indent) {
      for (i <- 0 to (indent - column - 1)) {
        super.write(' ')
        column = indent
      }
    }
    super.write(c)
    column += 1
  }
  
  override def println(): Unit = {
    super.println()
    column = 0
  }
  
  override def write(value: String): Unit = {
    if (column < indent) {
      for (i <- 0 to (indent - column - 1)) {
        super.write(' ')
        column = indent
      }
    }
    super.write(value)
    column += value.length()
  }
  
  def indent[T](f: => T): T = indentBy(indentSize)(f)
  
  def indentBy[T](columns: Int)(f: => T): T = {
    val oldIndent = indent
    indent += columns
    try {
      f
    } finally {
      indent = oldIndent
    }
  }
}

object IndentPrintWriter {
  def main(args: Array[String]): Unit = {
    val out = new IndentPrintWriter(new PrintWriter(System.out))
    out.println("Hello world")
    out.indent {
      out.println("hi")
      out.println(1.0)
    }
    out.println("moo")
  }
}
